#!/bin/bash

# SPDX-FileCopyrightText: 2022 - 2023 UnionTech Software Technology Co., Ltd.
#
# SPDX-License-Identifier: GPL-3.0-or-later

# Reference:
# https://wikidev.uniontech.com/%E8%BF%9B%E7%A8%8B%E8%BF%90%E8%A1%8C%E6%9D%83%E9%99%90%E4%B8%8E%E6%8F%90%E6%9D%83
function get_scale_factor() {
    user_name=$(logname)
    scaling=$(sudo -u "$user_name" dbus-launch gsettings get com.deepin.xsettings scale-factor)

    if (( $(bc <<< "$scaling >= 1 && $scaling <= 10") )); then
        echo $scaling
    else
        echo "Error: Invalid scaling factor: $scaling" >&2
        echo 1
    fi
}

function run_pkexec() {
        xhost +SI:localuser:root
        echo "run in pkexec: $@"
        pkexec --disable-internal-agent "$@" `id -u`
        xhost -SI:localuser:root
        xhost
}

function run_app() {
        echo "param in run_app: $@"
        user_name=$(logname)
        uid=$(id -u "$user_name")
        echo "runner uid: $uid"
        export XDG_RUNTIME_DIR=/run/user/$uid
        export WAYLAND_DISPLAY=wayland-0
        export DISPLAY=:0
        export QT_WAYLAND_SHELL_INTEGRATION=kwayland-shell
        export XDG_SESSION_TYPE=wayland
        export QT_QPA_PLATFORM=
        export GDK_BACKEND=x11
        export $(dbus-launch)

        scale_factor=$(get_scale_factor)
        if [ "$scale_factor" != "1" ]; then
            echo "export scaling: $scale_factor"
            export QT_SCALE_FACTOR=$scale_factor
        fi

        dde-file-manager "$1" -w "$(pwd)"
}

echo "run dde-file-manager in $XDG_SESSION_TYPE"
if [ "$XDG_SESSION_TYPE" == "x11" ];then
        pkexec dde-file-manager "$@" -w `pwd`
else
        echo "current file: $0"
        if [ x$(id -u) != "x0" ];then
                run_pkexec "$0" "$@"
                exit 0
        fi

        echo "run app: $@"
        run_app "$@"
fi
